package ControlLayer;

import java.util.ArrayList;

import DBLayer.DBConnection;
import DBLayer.DBCustomer;
import DBLayer.IFDBCustomer;
import ModelLayer.Customer;
import ModelLayer.Discount;
import ModelLayer.Enum;

public class CustomerCtr {
	private DiscountCtr discountCtr;

	public CustomerCtr() {
		discountCtr = new DiscountCtr();
	}

	public Customer getCustomer(int customerId) {
		IFDBCustomer dbCustomer = new DBCustomer();
		return dbCustomer.getCustomer(customerId, true);
	}

	public int insertCustomer(String name, String address, String city,
			int phone, int postCode, String customerType, int discountId) {
		int customerID = 0;
		Customer customerObj = new Customer();
		customerObj.setName(name);
		customerObj.setAddress(address);
		customerObj.setPhone(phone);
		customerObj.setPostCode(postCode);
		customerObj.setCity(city);
		customerObj.setCustomerType(Enum.valueOf(customerType));
		customerObj.setDiscount(new Discount(discountId));
		try {
			DBConnection.startTransaction();
			DBCustomer dbCustomer = new DBCustomer();
			customerID = dbCustomer.insertCustomer(customerObj);
			DBConnection.commitTransaction();
		} catch (Exception e) {
			DBConnection.rollbackTransaction();
		}
		
		return customerID;

	}

	public ArrayList<Customer> getAllCustomer() {
		IFDBCustomer dbCustomer = new DBCustomer();
		ArrayList<Customer> customers = new ArrayList<Customer>();
		customers = dbCustomer.getAllCustomers(false);
		return customers;
	}

	public int updateCustomer(int customerId, String name, String address,
			String city, int phone, int postCode, String customerType,
			int discountId) {
		IFDBCustomer dbCustomer = new DBCustomer();
		Customer customerObj = new Customer();
		customerObj.setId(customerId);
		customerObj.setName(name);
		customerObj.setAddress(address);
		customerObj.setPhone(phone);
		customerObj.setPostCode(postCode);
		customerObj.setCity(city);
		customerObj.setCustomerType(Enum.valueOf(customerType));
		customerObj.setDiscount(discountCtr.getDiscount(discountId));
		return dbCustomer.updateCustomer(customerObj);
	}

	public int deleteCustomer(int customerId) {
		IFDBCustomer dbCustomer = new DBCustomer();
		int rc = dbCustomer.deleteCustomer(customerId);
		if (rc != -1)
			return 1;
		else return 2;
	}

}
